﻿package  com.flashdynamix.utils{
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	public class Util {
		import flash.utils.ByteArray;
		public function Util() {
		}
		public static const SERVER:String = "";

		/**
		 * 20130304
		 * @param Number
		 * @return 
		 */		
		public static function getDateStr(t:Number):String {
			var year:String; 
			var month:String;
			var date:String;
			var d:Date = new Date(t);
			year = ""+d.getFullYear();
			month = addZero(d.getMonth() + 1);
			date =  addZero(d.getDate());
			return year+month+date;
		}
		
		/**
		 * 20130304
		 * @param currDate
		 * @return 
		 * 
		 */		
		public static function getSysYMDDateStr(currDate:Date = null):String {
			var year:String; 
			var month:String;
			var date:String;
			var d:Date = currDate;
			if (currDate == null) d = new Date();
			year = ""+d.getFullYear();
			month = addZero(d.getMonth() + 1);
			date =  addZero(d.getDate());
			return year+""+month+""+date;
		}
		
		/**
		 * 2013-03-04 15:39:49 
		 * @param Number
		 * @return 
		 * 
		 */		
		public static function getSysDate(t:Number):String {
			var year:String;
			var month:String;
			var date:String;
			var hour:String;
			var minute:String;
			var second:String;
			var d:Date = new Date(t);
			year = (""+d.getFullYear());
			month = addZero(d.getMonth() + 1);
			date =  addZero(d.getDate());
			hour =  addZero(d.getHours());
			minute= addZero(d.getUTCMinutes());
			second= addZero(d.getUTCSeconds());
			return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
		}
		
		private static function addZero(value:int):String {
			return value < 10?("0" + value):String(value)
		}
		
		/**
		 * 2013-03-04 15:34:55
		 * @param date
		 * @param useHours
		 * @return 
		 */		
		public static function dateToMyString(date:Date,useHours:Boolean=true):String {
			var str:String= date.fullYear + "-" + getNum(date.month+1) + "-" + getNum(date.date)
			if(useHours)str+=" "+getNum(date.hours)+":"+getNum(date.minutes)+":"+getNum(date.seconds)
			return str
			function getNum(value:int):String {
				return value < 10?("0" + value):String(value)
			}
		}
		
		//格式化时间显示
		public static function formatTime(time:Number):String {
			var tempDate:Date = new Date(time);
			var tempHours:String = tempDate.getUTCHours()<10 ? "0"+tempDate.getUTCHours() : ""+tempDate.getUTCHours();
			var tempMinutes:String = tempDate.getUTCMinutes()<10 ? "0"+tempDate.getUTCMinutes() : ""+tempDate.getUTCMinutes();
			return tempHours.concat(":",tempMinutes);
		}
		//格式化时间显示formatTimeHMS
		public static function formatTimeHMS(time:Number):String {
			var tempDate:Date = new Date(time);
			var tempHours:String = tempDate.getUTCHours()<10 ? "0"+tempDate.getUTCHours() : ""+tempDate.getUTCHours();
			var tempMinutes:String = tempDate.getUTCMinutes()<10 ? "0"+tempDate.getUTCMinutes() : ""+tempDate.getUTCMinutes();
			var tempSeconds:String = tempDate.getUTCSeconds()<10 ? "0"+tempDate.getUTCSeconds() : ""+tempDate.getUTCSeconds();
			return tempHours.concat(":",tempMinutes,":",tempSeconds);
		}
		//格式化浮点数显示
		public static function formatNumber(num:Number):String {
			num +=0.00;
			var str:String = num.toFixed(2);
			if(str.charAt(str.length-1)=="0" && str.charAt(str.length-2)=="0")
				str = str.substring(0,str.length-3);
			return str;
		}
		//计算倒计时 HH:SS
		public static function countDown(t:Number):String {
			if(t>=0) {
				var hh:int = int(t/3600000);
				var mm:int = int((t%3600000)/60000);
				var ss:int = int((t%60000)/1000);
				var hhStr:String = hh<10?"0"+hh:""+hh;
				var mmStr:String = mm<10?"0"+mm:""+mm;
				var ssStr:String = ss<10?"0"+ss:""+ss;
				return hhStr.concat(":",mmStr,":",ssStr);
			}
			return "";
		}
		public static function readLong(byteArray:ByteArray):Number {
			if(byteArray.bytesAvailable >= 8) {
				var u1:uint, u2:uint;
				u1=byteArray.readUnsignedInt();
				u2=byteArray.readUnsignedInt();
				var total:Number;
				total = Number(u1);
				total = total *4294967296;
				total += u2;
				//trace("取到时间为:"+new Date(total));
				return total;
			}
			else {
				trace("Function longToNumber ByteArray[8]长度不能为:"+byteArray.bytesAvailable);
				return 0;
			}
		}
		
		public static function writeLong(byteArray:ByteArray,longInt:Number):void {
			var t1:uint, t2:uint;
			t1 =longInt;
			t2 = longInt/4294967296;
			byteArray.writeUnsignedInt(t2);
			byteArray.writeUnsignedInt(t1);
		}
		/**
		 *	关闭当前页面并打开一个新的URL
		 *	param url:需要打开的url
		 *	param type:
		 */
		public static function go(url:String):void {
			url="javascript:window.open('"+url+"','win"+ windowCounter++ +"');void(0);window.close();";
			trace(url);
			var request:URLRequest = new URLRequest(url);
			try {
				navigateToURL(request,"_self");
			} catch (e:Error) {
				// handle error here
			}
		}		
		
		/**
		 *	在新的浏览器中打开一个URL
		 *	param url:需要打开的url
		 *	param type:
		 */
		private static var windowCounter:int = 0;
		public static function openURL(url:String, type:String = "_self"):void 
		{
			url="javascript:window.open('"+url+"','win"+ windowCounter++ +"'); void(0);";
			trace(url);
			var request:URLRequest = new URLRequest(url);
			try {
				navigateToURL(request, type);
			} catch (e:Error) {
				// handle error here
			}
		}
		
		/**
		 *	在新的浏览器中打开一个URL
		 *	param url:需要打开的url
		 *	param type:
		 */
		public static function getURL(url:String, type:String = "_self"):void 
		{
			trace(url);
			var request:URLRequest = new URLRequest(url);
			try {
				navigateToURL(request, type);
			} catch (e:Error) {
				// handle error here
			}
		}
		
		/**
		 *	在当前浏览器中打开一个URL
		 *	param url:需要打开的url
		 *	param type:
		 */
		public static function gotoURL(url:String):void {
			url="javascript:location.reload('"+url+"');";
			trace(url);
			var request:URLRequest = new URLRequest(url);
			try {
				navigateToURL(request,"_self");
			} catch (e:Error) {
				// handle error here
			}
		}
		
		/**
		 *	重新加载
		 *	param url:需要打开的url
		 *	param type:
		 */
		public static function reload():void {
			var url:String="javascript:location.reload();";
			var request:URLRequest = new URLRequest(url);
			try {
				navigateToURL(request,"_self");
			} catch (e:Error) {
				// handle error here
			}
		}
		
		//字符串转换成unicode映射
		public static function unicode_escape(string:String):String {
			var _string:String = string;
			var _arr:Array = new Array();
			for (var n:Number = 0; n<_string.length; n++) {
				_arr[n] = "0x"+_string.charCodeAt(n).toString(16);
			}
			_string = _arr.join("/");
			return _string;
		}
		//trace(unicode_escape("ab：c&*^&("));
		//unicode解码成字符串
		public static function unicode_unescape(string:String, delimiter:String):String {
			var _string:String = string;
			var _arr:Array = _string.split(delimiter);
			for (var n:Number = 0; n<_arr.length; n++) {
				_arr[n] = String.fromCharCode(_arr[n]);
			}
			_string = _arr.join("");
			return _string;
		}
		//trace(unicode_unescape("0x61/0x62/0xff1a/0x63/0x26/0x2a/0x5e/0x26/0x28", "/"));
		public static function byArrayToString(byArray:ByteArray):String  
		{  
			byArray.position = 0;  
			var strReturn:String = new String();  
			for(var i:int = 0; i < byArray.length / 2; ++i)  
			{  
				var strRep:String = byArray.readMultiByte(2, "unicode");  
				strReturn = replaceAt(strReturn, strRep, i, i);  
			}  
			return strReturn;  
		} 
		
		
		//unicode string to ByteArray                                                       
		public static function StrToByteArray( strValue:String, uLen:uint = 0 ):ByteArray  
		{                                                                                  
			var byAaryR:ByteArray = new ByteArray();                                       
			byAaryR.endian = Endian.LITTLE_ENDIAN;                                         
			for ( var i:int = 0; i < strValue.length; ++i )                                
			{                                                                              
				byAaryR.writeShort(strValue.charCodeAt(i));                                
			}                                                                              
			for ( i = 0; i < (uLen - strValue.length); ++i )                               
			{                                                                              
				byAaryR.writeShort(0);                                                     
			}                                                                              
			return byAaryR;                                                                
		}  
		
		
		public static function replaceAt(char:String, value:String, beginIndex:int, endIndex:int):String   
		{  
			beginIndex = Math.max(beginIndex, 0);  
			endIndex = Math.min(endIndex, char.length);  
			var firstPart:String = char.substr(0, beginIndex);  
			var secondPart:String = char.substr(endIndex, char.length);  
			return (firstPart + value + secondPart);  
		} 	
		
		public static function strToUnicode(src:String):String   
		{
		var des:String = "";
		var tmpbytearr:ByteArray = new ByteArray();
		tmpbytearr.writeMultiByte(src, "GBK");//参看注解四
		tmpbytearr.position = 0;//重要！！！参看注解1
		for (var j:int=0; j<tmpbytearr.length; j++)
		{
			des += tmpbytearr.readUnsignedByte().toString(16);
		}
		trace(des);//d6d0cec4
		/*注解一：bytearray的read和write都是从position处开始，而read会导致position变到读取结束处，write也会导致position变到写入结束处，如果在read或者write操作后注意position的归位，运行将出现Error #2030！
		注解二：writeMultiByte(src, "utf-8")等价于writeUTFBytes
		注解三：bytearray的tostring方法，如果usecodepage是true，会按照codepage解码bytearray；否则按照utf-8解码输出
		注解四：writeMultiByte(src, charset)的过程，循环对src中的每一个字符进行如下动作，对每一个字符的unicode编码查找charset的codepage，得到charset对应的该字符编码！所以如果某个字符的在charset字符集中不存在，转换得到的是3f，也就是一个问号！*/ 
		return des;  
		} 	
		
		

	}
}